import ProcedureBase from "../../game_framework/fsm/ProcedureBase"
import Log from "../../game_framework/utils/Log"
import App from "../../game_framework/App"
import LoginScene from "../scene/LoginScene"
import { SceneConsts } from "../consts/SceneConsts"
import GlobalInfo from "../../game_framework/consts/GlobalInfo"
import ResourceItem from "../../game_framework/resource/ResourceItem"
import { isNull } from "../../game_framework/utils/GlobalDefine"
import LayerManager from "../../game_framework/layer/LayerManager"
import ProcedureCheckVersion from "./ProcedureCheckVersion"

/** 加载过程，期间可能加载资源，参数等等 */
export default class ProcedureLaunch extends ProcedureBase {
    constructor(owner: Object) {
        super(owner)
    }

    public onInit(...args: any[]): void {
        super.onInit(args)
    }

    public onEnter(obj: Object = null): void {
        super.onEnter(obj)
        // 读取到url 中的参数
        App.UrlParameters = this.urlParse()
        // 读取游戏的全局配置
        App.ResMgr.loadRes("config/build_info", cc.JsonAsset, this.onBuildInfoConfigLoadComplete.bind(this))
        // TODO: 可能还有其他配置等需要加载，比如：读取服务端设置的其他支付等配置
        // TODO 。。。。。。
    }
    /**
     * 游戏打包的配置加载好后的处理
     * @param err 
     * @param res 
     */
    private onBuildInfoConfigLoadComplete(err: string, res: ResourceItem): void {
        if (isNull(err)) {
            App.BuildInfo = res.getRes().json
            console.log("App.BuildInfo = ", App.BuildInfo)
            console.log("App.UrlParameters = ", App.UrlParameters)
            // 框架初始化
            App.init()
            // 网关等信息设置
            App.GlobalInfo = new GlobalInfo()
            App.GlobalInfo.GateServerIp = "121.40.165.18"
            App.GlobalInfo.GateServerPort = 8800
            // fui 的初始化
            fgui.addLoadHandler()
            fgui.GRoot.create()
            // 初始化UI界面管理者
            LayerManager.init()
            // 初始化场景类
            this.initScene()
            // 进入下一步流程：检查版本
            App.Procedure.changeState(cc.js.getClassName(ProcedureCheckVersion))
        } else {
            console.log(err)
        }
    }

    public onUpdate(): void {
        super.onUpdate()
    }

    public onLeave(preKey: string): void {
        super.onLeave(preKey)
    }
    /**
     * 读取当前URL上的参数
     * @returns 
     */
    private urlParse(): Object {
        if (window.location == null) { return {} }
        return App.Http.decode(window.location.href)
    }

    /**
     * 初始化所有场景
     */
    private initScene(): void {
        // 注册登录场景
        App.SceneMgr.register(SceneConsts.Login, new LoginScene())
    }
}
